/**
 * 使用高德地图WebSDK 定位、获取城市
 */
import { sortBy } from 'lodash-es';
import AMapLoader from '@amap/amap-jsapi-loader';

const options = {
  key: '6f7016c0ba9d90ce3122225bf7fbd3ce', // 申请好的Web端开发者Key，首次调用 load 时必填
  version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  plugins: ['AMap.Geolocation', 'AMap.CitySearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
};

const spcelProvince = ['北京市', '天津市', '上海市', '重庆市'];

/**
 * 获取定位（省市区，精度）
 * @returns 返回 { city, province, district, lat, lng }
 */
export const getGeolocationByGaoDe = () => {
  return AMapLoader.load(options).then((AMap) => {
    return new Promise((resolve, reject) => {
      AMap.plugin('AMap.Geolocation', function () {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: false,
          timeout: 10 * 60 * 1000,
        });

        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', (res) => {
          const { lat, lng } = res.position;
          const { province, district } = res.addressComponent;
          const isSpeclProvince = spcelProvince.includes(province);
          let city = res.addressComponent.city;
          if (!city && district) city = district;
          if (isSpeclProvince) city = province;

          resolve({ lat, lng, city, province, district });
        });
        AMap.event.addListener(geolocation, 'error', reject);
      });
    });
  });
};

/**
 * 获取 城市信息，没有精度
 * 快速，不需要定位
 * @returns 返回 { city, province }
 */
export const getAddressByGaoDe = () => {
  return AMapLoader.load(options).then((AMap) => {
    return new Promise((resolve, reject) => {
      AMap.plugin('AMap.CitySearch', function () {
        const citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            const { district, province } = result;
            const isSpeclProvince = spcelProvince.includes(province);
            let city = result.city;
            if (!city && district) city = district;
            if (isSpeclProvince) city = province;
            resolve({ city, province });
          } else {
            reject(result);
          }
        });
      });
    });
  });
};

/**
 * 计算两个地理坐标之间的距离
 * @param {*} lat1
 * @param {*} lng1
 * @param {*} lat2
 * @param {*} lng2
 * @returns 千米
 */
export const calcGeoSpace = (lat1, lng1, lat2, lng2) => {
  const radLat1 = (lat1 * Math.PI) / 180.0;
  const radLat2 = (lat2 * Math.PI) / 180.0;
  const a = radLat1 - radLat2;
  const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
  let s =
    2 *
    Math.asin(
      Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)),
    );
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s;
};

/**
 * 计算距离并按距离排序
 * @param {array} list 体检中心列表
 * @param {number} lat
 * @param {number} lng
 * @returns
 */
export const getDistanceAndSort = (list, lat, lng) => {
  const res = list.map((v) => {
    if (v.address && v.address.latitude) {
      const { longitude, latitude } = v.address;
      const distance = calcGeoSpace(lat, lng, latitude, longitude);
      v.distance = parseFloat(distance.toFixed(2));
    } else {
      v.distance = 0;
    }
    return v;
  });
  return sortBy(res, 'distance');
};
